// CSE 142 Winter 2008, Marty Stepp // This program demonstrates the "cumulative sum" technique // with a method that computes the sum of a range of integers. // public class Sums { public static void main(String[] args) { System.out.println("The sum is " + sumTo(1000)); System.out.println("Here's another sum! " + sumTo(100)); System.out.println("The sum to 100000 plus the sum to 54 is " + (sumTo(100000) + sumTo(54))); } // This method computes the sum of all the integers // between 1 and the given max value. // It returns its result as an int. // I assume that the max passed is >= 1. public static int sumTo(int max) { // for each of the numbers from 1-1000, // add that number to a total sum... // "cumulative sum" variable int sum = 0; // 0 -> 1 -> 3 -> 6 -> 10 -> 15 for (int i = 1; i <= max; i++) { sum = sum + i; } return sum; } }